const Sequelize = require('sequelize');
const bcrypt = require('bcryptjs');

module.exports = function (sequelize, DataTypes) {
  const Users = sequelize.define('Users', {
    id: {
      autoIncrement: true,
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      primaryKey: true
    },
    username: {
      type: DataTypes.STRING(255),
      allowNull: false,
      unique: {
        msg: '该用户名已经被使用，请选择其他用户名。'
      },
      comment: "账号"
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false, // 不允许为空
      validate: {
        len: {
          args: [6, 18],
          msg: '密码长度必须为6到18位。'
        },
        containsLetter(value) {
          if (!/[a-zA-Z]/.test(value)) {
            throw new Error('密码必须包含至少一个字母。');
          }
          this.setDataValue('password', bcrypt.hashSync(value, 10));
        }
      },
      comment: "密码"
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: false,
      unique: {
        msg: '该邮箱已经被注册，请使用其他邮箱。'
      },
      validate: {
        isEmail: {
          msg: '请输入有效的邮箱地址。'
        }
      },
      comment: "邮箱"
    },
    user_url: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "头像地址"
    },
    sex: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "性别"
    },
    nikename: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "昵称"
    },
    lastlogindate: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: "登陆时间"
    },
    user_uid: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "uid"
    },
    login_address: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "ip地址"
    },
    user_signature: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "个性签名"
    },
    Interests: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "数组记录用户感兴趣的类型"
    },
    permissions: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "0普通用户，1管理员，2官方账号"
    },
    user_status: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: "状态，0正常1封禁"
    }
  }, {
    sequelize,
    tableName: 'Users',
    timestamps: true,
    indexes: [
      {
        name: "PRIMARY",
        unique: true,
        using: "BTREE",
        fields: [
          { name: "id" },
        ]
      },
    ]
  });

  Users.associate = function (models) {
    Users.belongsToMany(models.Articles, {
      through: models.Likes,
      foreignKey: 'userid', // 将 Likes 表中的 postid 字段与 Articles 表关联
      otherKey: 'postid', // 将 Likes 表中的 userid 字段与 Users 表关联
      as: 'likeArticles'
    });
  };



  return Users;
};
